<?php namespace App\Controllers;

use \App\App;
use App\Models\Story;
use App\Models\Api;

class Category extends App
{

    public function __construct()
    {
        parent::__construct();
    }

    public function index($id = null)
    {
        $this->view->type = $this->request->request("type");
        $this->view->page = $this->request->request("page");
        //$this->view->category = $id;
        $this->view->assets = $this->config->baseUrl . "/assets";
        $categoryModel = new \App\Models\Category();
        $this->view->sub = $categoryModel->where("parent", $id)->findAll();

        $this->view->list = $this->get($id, true);

        $this->render("/front/category/category", "/front/header");
    }

    function get($id = null, $string = false)
    {
        $type = $this->request->request("type");
        $page = $this->request->request("page") ?: 0;

        $categoryModel = new \App\Models\Category();
        $category = $categoryModel->find($id);
        if ($category['parent'] != 0) {
            $parent = $categoryModel->find($category['parent']);
            $where = ['category' => $parent['name'], 'sub_category' => $category['name']];
            $major = ["major" => $parent['name'], "minor" => $category['name']];
            $categoryTitle = [$parent, $category];
            $viewTitle = $parent['name'] . ' - ' . $category['name'];
        } else {
            $where = ['category' => $category['name']];
            $major = ["major" => $category['name']];
            $viewTitle = $category['name'];
            $categoryTitle = [$category];
        }

        if ($type  && $type == "cloud") {
            $api = new Api(1);
            $major['gender'] = "male";
            $major["type"] = "hot";
            $major["start"] = $page * 20;
            $major["limit"] = 20;
            $result = $api->getUrl("category", $major);
            $this->view->staticUrl = $api->getUrl('static', null, false);
        } else {
            $storyModel = new Story();
            $result = $storyModel->where($where)->limit(20, $page * 20)->datatable("total", "books", false);
        }
        $this->view->type = $type;
        $this->view->page = $page;
        $this->view->categoryTitle = $categoryTitle;
        $this->view->viewTitle = $viewTitle;
        $this->view->stories = $result;
        $this->view->category = $id;

        return $string ? $this->view->display("/front/category/list")->toString() : $this->render("/front/category/list", "/front/header");
    }
}
